package com.aust.state;

/**
 * 观察线程状态
 */
public class TestState {

    public static void main(String[] args) throws InterruptedException {

        Thread thread = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("----------------");
        });

        /**
         * 观察状态
         */
        Thread.State state = thread.getState();
        System.out.println(state); // NEW

        /**
         * 观察启动
         */
        thread.start();
        state = thread.getState();
        System.out.println(state); // RUN

        /**
         * 只要线程不终止，就一直输出状态
         */
        while (state != Thread.State.TERMINATED) {
            /**
             * 主线程每隔 1 秒获取一次 thread 的状态，并输出状态。
             */
            Thread.sleep(1000);
            state = thread.getState(); // 更新线程状态
            System.out.println(state);
        }

    }

}
